package org.mq.mymq.nameserver.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import org.mq.mymq.common.coder.TcpMsgDecoder;
import org.mq.mymq.common.coder.TcpMsgEncoder;
import org.mq.mymq.common.constants.TcpConstants;
import org.mq.mymq.common.event.EventBus;
import org.mq.mymq.nameserver.handler.TcpNettyServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName NameServerStarter
 * @Description 基于Netty启动nameserver服务
 * @Author jiarong_ye
 * @Date 2025/6/18 18:57
 * @Version 1.0
 */
public class NameServerStarter {
    private static final Logger log = LoggerFactory.getLogger(NameServerStarter.class);
    private int port;
    public NameServerStarter(int port) {
        this.port = port;
    }
    public void startServer() throws InterruptedException {
        // 构建Netty服务
        // 注入编解码器
        // 注入特定的handler
        // 启动Netty服务
        // 处理网络io中的accept时间
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // 处理网络IO中的read/write事件
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel channel) throws Exception {
                ByteBuf delimiter = Unpooled.copiedBuffer(TcpConstants.DEFAULT_DECODE_CHAR.getBytes());
                channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024 * 8, delimiter));
                channel.pipeline().addLast(new TcpMsgDecoder());
                channel.pipeline().addLast(new TcpMsgEncoder());
                channel.pipeline().addLast(new TcpNettyServerHandler(new EventBus("broker-connection-")));
            }

        });
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            log.info("nameserver is closed");
        }));
        ChannelFuture channelFuture = bootstrap.bind(port).sync();
        log.info("start nameserver application on port {}", port);
        channelFuture.channel().closeFuture().sync();
    }
}
